from django.conf import settings
from django.shortcuts import render_to_response
from contifyuser.models import Member
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.template import RequestContext
from django.contrib.auth import logout
from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from contifyuser.forms import RegistrationFormConnectPeople, photoUploadForm, editProfileForm
from StartGroup.models import Group
from groupMembers.models import Member_Group, group_mem_assoc_v
import Constants
import connectpeople.Constants
import simplejson
from django.http import HttpResponse
from django.core.cache import cache
from utils import common_query, activity_module, common_methods
from django import forms
from django.contrib.admin.widgets import AdminFileWidget
from django.http import QueryDict
from django.utils.safestring import mark_safe
import neo4j
import datetime

# Home page view will add to it later 
def home(request):
    render_template = Constants.contifyuser
    mem_grp_data = []
    member = ''
    action = ''
    # refresh cache data
    refreshCache = True
    if connectpeople.Constants.session_userid in request.session:
        userid = request.session[connectpeople.Constants.session_userid]

        # Delete the group through ajax call
        if request.method == 'POST':

            try:
                # Take the Action String to identif which action to perform
                action = request.POST.__getitem__('action')
            except:
                action = None
                
            if action == "Profile_Edit":
                # Edit user profile
                response = editprofile(request, userid)              
            elif action == "Picture_Upoad":
                # Upload image. Note the request.Files will be taken only when enctype
                # is defined in the form tag on html
                pic_form = photoUploadForm(data=request.POST, files=request.FILES)
                if pic_form.is_valid():
                    pic_form.save(Member.objects.get(user=User.objects.get(username=userid)))
            elif action == "Email_Settings_Update":
                # Update Email settings for user
                response = editEmailSettings(request, userid)
            elif action == "change_paswd":
                # Change Password
                message = changePassword(userid, request)
                response = simplejson.dumps({'message':message})
            elif action == "Delete_Group":
                # Get the group web address to be deleted
                gwebaddr = request.POST.__getitem__('gwebaddr')                    
                if gwebaddr:
                    # Delete the group from database
                    Group.objects.get(group_web_address=gwebaddr).delete()
                    # Set response to success
                    response = simplejson.dumps({'success':'success'})
            elif action == "NEW_DISCUSSION_ACTIVITY_COMMENT_POSTED":
                # Get comment and activity index. then save into node
                comment = request.POST.__getitem__('comment')
                acti_index = request.POST.__getitem__('acti_id')
                activity_module.setCommentNode(acti_index, comment, userid)
                response = simplejson.dumps({'success':'success'})
                # No need to refresh cache data
                refreshCache = False
            elif action == "NEW_DISCUSSION_ACTIVITY_LIKED":
                # Get comment and activity index, type and value. then save into node
                index = request.POST.__getitem__('index')
                type = request.POST.__getitem__('type')
                value = request.POST.__getitem__('value')
                activity_module.setOtherActivityNode(index, type, value, userid)
                # No need to refresh cache data                
                refreshCache = False
                response = simplejson.dumps({'success':'success'})
                
            if refreshCache == True:
                # Update mem_group_data        
                mem_grp_data = common_query.get_group_member(userid, True)
                
                # Get the list of initial checkbox values for emails settings
                emailinitList = emailChkboxList(mem_grp_data[0].email_setting)                
        else:            
            # Get the groups to which user is member
            mem_grp_data = common_query.get_group_member(userid, False)
        
            # Get the list of initial checkbox values for emails settings
            emailinitList = emailChkboxList(mem_grp_data[0].email_setting)
        
        if request.method == 'POST':
            # Update the calendar
            if action =="CALENDAR_UPDATE":
                year = action = request.POST.__getitem__('year')
                month = action = request.POST.__getitem__('month')
                cal_month = common_methods.getUserEventCal(mem_grp_data, int(year), int(month))
                response = simplejson.dumps({'cal_month': cal_month})        
        
        # Return the ajax response
        if request.is_ajax():
            return HttpResponse(response,
            content_type="application/javascript")
        
        # Photo upload form  
        pic_form = photoUploadForm()
        
        # Edit Profile form
        edit_profile_form = editProfileForm()
        
        # Get Activities related to user
        activity_dict = activity_module.getGroupActivities(mem_grp_data)
        
        # Get cal_month
        cal_month = common_methods.getUserEventCal(mem_grp_data, datetime.datetime.today().year, datetime.datetime.today().month)
        
        # My Profile
        isMyProfile = True
        
        render_template += Constants.view_profile_template
    else:
        activity_dict = []
        emailinitList = []
        cal_month = []
        pic_form = None
        edit_profile_form = None
        isMyProfile = False
        render_template += Constants.base_template
        
    return render_to_response(render_template, {connectpeople.Constants.signin_form_constant: AuthenticationForm(),
                            'mem_grp_data': mem_grp_data, 'pic_form': pic_form, 'edit_profile_form': edit_profile_form,
                            'activity_dict': activity_dict, 'cal_month':cal_month,
                            'isMyProfile': isMyProfile},
                            context_instance=RequestContext(request))

# Profile Settings
def profile_settings(request, userid):

    # Get the user info from database
    mem_grp_data = group_mem_assoc_v.objects.filter(userid=request.session[connectpeople.Constants.session_userid])
        
    # Photo upload form  
    pic_form = photoUploadForm()
    
    # Edit Profile form
    edit_profile_form = editProfileForm()
    
    # No activity display
    activity_dict = ''
    
    # Get the list of initial checkbox values for emails settings
    emailinitList = emailChkboxList(mem_grp_data[0].email_setting)  
    
    return render_to_response("contifyuser/profile_settings.html", {'mem_grp_data': mem_grp_data, 'pic_form': pic_form, 'edit_profile_form': edit_profile_form,
                            'activity_dict': activity_dict, 'emailChkboxList': emailinitList}, context_instance=RequestContext(request))

# Edit profile
def editprofile(request, userid):
    edit_profile_form = editProfileForm(data=request.POST)
    if edit_profile_form.is_valid():
        new_member = edit_profile_form.save(Member.objects.get(user=User.objects.get(username=userid)))
        response = simplejson.dumps({'firstName':new_member.first_name, 'lastName':new_member.last_name, 'city':new_member.city, 'country':new_member.country})
    else:    
        response = simplejson.dumps({'': ''})
    return response

# Edit Email Settings
def editEmailSettings(request, userid):
    member = Member.objects.get(user=User.objects.get(username=userid))

    # Get list of email setting flags
    posted_value = request.POST.getlist('email_settings_values[]')
    
    # Get the default value for email settings. These are defined in Constants.py of project
    default_settings = connectpeople.Constants.default_email_setting
    # Split string based on ";"
    individual_settings = default_settings.split(";")
    
    final_value = []
    count= 0
    for each in posted_value:
        final_value.append(individual_settings[count].split(":")[0] + ":"  + each + ";")
        count = count + 1
        
    member.email_settings = mark_safe(u''.join(final_value))
    # save value in database
    member.save()
    
    return simplejson.dumps({'success': 'success'})

# Compose list of initial checkbox values
def emailChkboxList(curr_email_settings):

    emailChkboxList =  []
    split_settings = curr_email_settings.split(";")
    for each in split_settings:
        if each:
            if each.split(":")[1] == "1":
                emailChkboxList.append("checked")
            else:
                emailChkboxList.append("")
    
    return emailChkboxList

# Change Password
def changePassword(userid, request):
    message = ""
    user = User.objects.get(username=userid)
    old_paswd = request.POST.__getitem__('old_paswd')
    new_paswd1 = request.POST.__getitem__('new_paswd1')
    new_paswd2 = request.POST.__getitem__('new_paswd2')
    if user.check_password(old_paswd) == True:
        if new_paswd1 == new_paswd2:
            try:
                user.set_password(new_paswd1)
                user.save()
                message = "confirmed"
            except:
                message = "Please enter valid password"
            
        else:
            message = "New Password and Confirm Password do not match"
    else:
        message = "Please correct Old Password"
    return message
    

# Sign in
def viewprofile(request):
    if request.method == 'POST':
        emailid = request.POST['username']
        password = request.POST['password']
        est_user = User.objects.get(email=emailid)
        username = est_user.username
        user = authenticate(username=username, password=password)        
        if user is not None:
            # Set a session value:
            request.session[connectpeople.Constants.session_userid] = username
            login(request, user)
            # if logged in then redirect to home page
            return redirect('/connectpeople/home')
        else:
            render_template = Constants.contifyuser + "/base.html"
            return render_to_response(render_template, {connectpeople.Constants.signin_form_constant: AuthenticationForm()},
                            context_instance=RequestContext(request))

# Process when logged in user is accessing
# different user's profile
def different_user_profile(request, userid):
    # Get the user info from database
    mem_grp_data = group_mem_assoc_v.objects.filter(userid=userid)
    
    # Get Activities performed by the user
    activity_dict = activity_module.getUserActivities(userid)
    
    # is user going to his/her profile
    isMyProfile = False
    if userid == request.session[connectpeople.Constants.session_userid]:
        isMyProfile = True
    
    return render_to_response("contifyuser/different_user_profile.html",
                              {'mem_grp_data':mem_grp_data, 'activity_dict': activity_dict, 'isMyProfile': isMyProfile},
                              context_instance=RequestContext(request))

def user_login(request):
    render_template = Constants.contifyuser + Constants.login_template
    return render_to_response(render_template, {connectpeople.Constants.signin_form_constant: AuthenticationForm()},
                            context_instance=RequestContext(request))
    
def logout_user(request):
    logout(request)
    response = redirect('/connectpeople/home/')
    return response       
    
# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)

# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)
    
# Helper function to obtain Groups related to a member
def getGroups(member):
    return Group.objects.filter(member_user = member)